{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "222c4363-1867-4b38-8980-56aa609d2d0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "chat = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", temperature=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "eca0b05d-56f0-4170-b40e-2d36843c1dd3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content=\"J'adore la programmation.\", response_metadata={'token_usage': {'completion_tokens': 8, 'prompt_tokens': 19, 'total_tokens': 27}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_592ef5907d', 'finish_reason': 'stop', 'logprobs': None}, id='run-5f63377a-4878-4173-9277-201111eb9c55-0')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "chat.invoke(\n",
    "    [\n",
    "        HumanMessage(\n",
    "            content=\"Translate this sentence from English to French: I love programming.\"\n",
    "        )\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4c7a766c-d23a-48c6-a3de-bfcce879d736",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='I apologize if there was any confusion. Can you please let me know what specific part of my previous response you would like me to clarify or repeat?', response_metadata={'token_usage': {'completion_tokens': 30, 'prompt_tokens': 13, 'total_tokens': 43}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_592ef5907d', 'finish_reason': 'stop', 'logprobs': None}, id='run-96a8be1d-43e1-4d13-96a0-6e0901e20539-0')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat.invoke([HumanMessage(content=\"What did you just say?\")])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "541b4cd9-01bb-45cd-8d21-f32fb90f5a4c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='I said \"J\\'adore la programmation\" which means \"I love programming\" in French.', response_metadata={'token_usage': {'completion_tokens': 21, 'prompt_tokens': 41, 'total_tokens': 62}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_592ef5907d', 'finish_reason': 'stop', 'logprobs': None}, id='run-5d2eb355-00cb-4137-ad84-992b3bff3a7b-0')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage\n",
    "\n",
    "chat.invoke(\n",
    "    [\n",
    "        HumanMessage(\n",
    "            content=\"Translate this sentence from English to French: I love programming.\"\n",
    "        ),\n",
    "        AIMessage(content=\"J'adore la programmation.\"),\n",
    "        HumanMessage(content=\"What did you just say?\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "750c36b5-856d-474a-8026-e158c00fda90",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are a helpful assistant. Answer all questions to the best of your ability. But at the end of every sentence, add a little joke.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "chain = prompt | chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "78ff74cd-3c22-4c49-9575-e6378c2fdcd1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='I said, \"J\\'adore la programmation.\" That\\'s French for \"I love programming.\" And I must say, that\\'s un peu magnifique!', response_metadata={'token_usage': {'completion_tokens': 33, 'prompt_tokens': 84, 'total_tokens': 117}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_77a673219d', 'finish_reason': 'stop', 'logprobs': None}, id='run-01e974d6-3d67-47d9-bda8-b7196656d9e7-0')"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke(\n",
    "    {\n",
    "        \"messages\": [\n",
    "            HumanMessage(\n",
    "                content=\"Translate this sentence from English to French: I love programming.\"\n",
    "            ),\n",
    "            AIMessage(content=\"J'adore la programmation.\"),\n",
    "            HumanMessage(content=\"What did you just say?\"),\n",
    "            HumanMessage(content=\"What did you just say?\"),\n",
    "        ],\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "8f7e3dc4-4132-4583-9e6c-9c56e530ab10",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='hi!'), AIMessage(content='whats up?')]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.memory import ChatMessageHistory\n",
    "\n",
    "demo_ephemeral_chat_history = ChatMessageHistory()\n",
    "\n",
    "demo_ephemeral_chat_history.add_user_message(\"hi!\")\n",
    "\n",
    "demo_ephemeral_chat_history.add_ai_message(\"whats up?\")\n",
    "\n",
    "demo_ephemeral_chat_history.messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c4988b74-98e7-40ee-98d7-d60fb1980677",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='Je adore la programmation. And I also love \"Ctrl\" and \"C\" because I always like to be in control and copy everything!', response_metadata={'token_usage': {'completion_tokens': 29, 'prompt_tokens': 66, 'total_tokens': 95}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_592ef5907d', 'finish_reason': 'stop', 'logprobs': None}, id='run-fddc67bb-4754-4fd7-9866-3faf82313362-0')"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demo_ephemeral_chat_history.add_user_message(\n",
    "    \"Translate this sentence from English to French: I love programming.\"\n",
    ")\n",
    "\n",
    "response = chain.invoke({\"messages\": demo_ephemeral_chat_history.messages})\n",
    "\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "13a6c8b4-9373-4a4d-bc40-baf3c32ca7b5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='I said \"Je adore la programmation,\" which means \"I love programming\" in French. And then I added a little joke about \"Ctrl\" and \"C\" because I always like to be in control and copy everything!', response_metadata={'token_usage': {'completion_tokens': 46, 'prompt_tokens': 109, 'total_tokens': 155}, 'model_name': 'gpt-3.5-turbo-1106', 'system_fingerprint': 'fp_592ef5907d', 'finish_reason': 'stop', 'logprobs': None}, id='run-f9758e0e-bd47-4f16-b022-20920cd218e4-0')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demo_ephemeral_chat_history.add_ai_message(response)\n",
    "\n",
    "demo_ephemeral_chat_history.add_user_message(\"What did you just say?\")\n",
    "\n",
    "chain.invoke({\"messages\": demo_ephemeral_chat_history.messages})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "0d1418be-467c-4c9b-9464-0bd2e2423804",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "\n",
    "loader = WebBaseLoader(\"https://docs.smith.langchain.com/overview\")\n",
    "data = loader.load()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "b0233b5f-a6e4-481b-ae94-8adca9e1d340",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)\n",
    "all_splits = text_splitter.split_documents(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "006c09b8-52df-49db-a5d5-9076bfbb5e72",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "3720860a-7713-49c6-802b-e9d0bf34616b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "16"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(all_splits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "57db6a3b-a581-40d8-850b-25b2e0b42191",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<langchain_community.vectorstores.chroma.Chroma at 0x116d13e90>"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())\n",
    "vectorstore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "dec395c6-ef81-4e5d-a456-f49cdd1f435b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Document(page_content='Getting started with LangSmith | 🦜️🛠️ LangSmith', metadata={'description': 'Introduction', 'language': 'en', 'source': 'https://docs.smith.langchain.com/overview', 'title': 'Getting started with LangSmith | 🦜️🛠️ LangSmith'}),\n",
       " Document(page_content='Getting started with LangSmith | 🦜️🛠️ LangSmith', metadata={'description': 'Introduction', 'language': 'en', 'source': 'https://docs.smith.langchain.com/overview', 'title': 'Getting started with LangSmith | 🦜️🛠️ LangSmith'}),\n",
       " Document(page_content='Skip to main contentLangSmith API DocsSearchGo to AppQuick StartUser GuideTracingEvaluationProduction Monitoring & AutomationsPrompt HubProxyPricingSelf-HostingCookbookQuick StartOn this pageGetting started with LangSmithIntroduction\\u200bLangSmith is a platform for building production-grade LLM applications. It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence. Use of LangChain is not necessary - LangSmith works on its own!Install LangSmith\\u200bWe', metadata={'description': 'Introduction', 'language': 'en', 'source': 'https://docs.smith.langchain.com/overview', 'title': 'Getting started with LangSmith | 🦜️🛠️ LangSmith'}),\n",
       " Document(page_content='Skip to main contentLangSmith API DocsSearchGo to AppQuick StartUser GuideTracingEvaluationProduction Monitoring & AutomationsPrompt HubProxyPricingSelf-HostingCookbookQuick StartOn this pageGetting started with LangSmithIntroduction\\u200bLangSmith is a platform for building production-grade LLM applications. It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence. Use of LangChain is not necessary - LangSmith works on its own!Install LangSmith\\u200bWe', metadata={'description': 'Introduction', 'language': 'en', 'source': 'https://docs.smith.langchain.com/overview', 'title': 'Getting started with LangSmith | 🦜️🛠️ LangSmith'})]"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# k is the number of chunks to retrieve\n",
    "retriever = vectorstore.as_retriever(k=4)\n",
    "\n",
    "docs = retriever.invoke(\"how can langsmith help with testing?\")\n",
    "\n",
    "docs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "dd3b89ae-8496-4ac3-8c92-dfbd99740320",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.combine_documents import create_stuff_documents_chain\n",
    "\n",
    "chat = ChatOpenAI(model=\"gpt-3.5-turbo-1106\")\n",
    "\n",
    "question_answering_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"Answer the user's questions based on the below context:\\n\\n{context}\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "document_chain = create_stuff_documents_chain(chat, question_answering_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "0cd3cef8-7ea5-4c45-b6bc-2f00835f9bcf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'LangSmith can help with testing by providing tools for closely monitoring and evaluating your application during the testing phase. It allows you to track and analyze the performance of your application, identify any potential issues or bottlenecks, and ensure that your application is ready for production. With LangSmith, you can gain confidence in the quality and reliability of your application before shipping it.'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.memory import ChatMessageHistory\n",
    "\n",
    "demo_ephemeral_chat_history = ChatMessageHistory()\n",
    "\n",
    "demo_ephemeral_chat_history.add_user_message(\"how can langsmith help with testing?\")\n",
    "\n",
    "document_chain.invoke(\n",
    "    {\n",
    "        \"messages\": demo_ephemeral_chat_history.messages,\n",
    "        \"context\": docs,\n",
    "    }\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
